//
//  deviceSelector.m
//  TI BLE SensorTag Example
//
//  Created by Ole Andreas Torvmark on 11/15/12.
//  Copyright (c) 2012 Texas Instruments. All rights reserved.
//

#import "deviceSelector.h"
#import "BLEUtility.h"
#import "AppDelegate.h"

@interface deviceSelector ()
    
@end

@implementation deviceSelector
@synthesize mCentralManager,nDevices,nLastConnDevices;

/*
 这个界面设计,因为是一个一个设备连接的, 即使搜索到多个设备, 也是不可能一下子都连接上的, 故暂时不自定义cell的形式来区分每个设备.
 */

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        self.mCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
        
        self.nDevices = [[NSMutableArray alloc]init];
        self.nLastConnDevices=[[NSMutableArray alloc] init];
        
        mCurrentConnectPeripheral=NULL;
        self.title = @"两组RGBDemo";
        [self setEditing:YES animated:YES];
        isReScan=NO;
        
        //30分钟发送一次
        mSendSyncCmdTimer =[NSTimer scheduledTimerWithTimeInterval: 30*60
                                                            target: self
                                                          selector: @selector(sendSyncCmdPkg:)
                                                          userInfo: nil
                                                           repeats: YES];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _settingBtn=[[UIBarButtonItem alloc] initWithTitle:@"开始演示" style:UIBarButtonItemStyleDone target:self action:@selector(doSetting:)];
    
    self.navigationItem.rightBarButtonItem=_settingBtn;
    
    _reScanBtn=[[UIBarButtonItem alloc] initWithTitle:@"扫描" style:UIBarButtonItemStyleDone target:self action:@selector(doReScan:)];
    self.navigationItem.leftBarButtonItem=_reScanBtn;
   
}
-(void)viewDidUnload
{
    NSLog(@"viewWill viewDidUnload---------");
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated {
    self.mCentralManager.delegate = self;
    isJustOpen=YES;
       NSLog(@"viewWill  viewWillAppear------------");
   int count=[self getLastConnecteDevice];
    if (count>0) {
        isAutoConnMode=YES;
    }else{
        isAutoConnMode=NO;
    }
}
-(void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"viewWill Dis Appear--------------");
    [self saveConnectedDevice];
}
#pragma mark 重新开始扫描.
- (void)doReScan:(id)sender{

        isJustOpen=NO;
     if(mCentralManager==nil)
     {
         return ;
     }
    isReScan=YES;
    
    
    [self.nDevices removeAllObjects];
    [self.tableView reloadData];
    
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    for (int i=0; i<[myDelegate.peripheralArray count]; i++)
    {
        CBPeripheral *peripheral=[myDelegate.peripheralArray objectAtIndex:i];
        
        [self.mCentralManager cancelPeripheralConnection:peripheral];  //开始断开.
    }
    //因断开后,会删除peripheralArray中的内容,这里不再对peripheralArray删除.
    usleep(400*1000);
    [mCentralManager scanForPeripheralsWithServices:nil options:nil];  //开始搜索

}
#pragma mark 开始演示
- (void)doSetting:(id)sender{
    [BLEUtility printConnectedCnt];
    SensorTagApplicationViewController *vC=[[SensorTagApplicationViewController alloc]initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:vC animated:YES];
    vC.title=@"演示功能";
  //  [BLEUtility deleteBondPasswd];
}

#pragma mark - Table view data source

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return nDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   // NSString *CellIdentifier = [NSString stringWithFormat:@"%d_Cell",indexPath.row];
    
   /// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //if(cell==nil){
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:[NSString stringWithFormat:@"%d_Cell",indexPath.row]];
    
        CBPeripheral *p = [self.nDevices objectAtIndex:indexPath.row];
        cell.textLabel.text = p.name;
    
        NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, p.UUID)];
        cell.detailTextLabel.text =strUUID;
    
    cell.tag=indexPath.row;
    UISwitch   *switchlight = [[UISwitch alloc] initWithFrame:CGRectMake(230, 0, 44, 44)];
  [switchlight addTarget:self action:@selector(switchBtnChanged:) forControlEvents:UIControlEventValueChanged];
   
    switchlight.tag=cell.tag;
    NSLog(@"switchlight tag:%d",switchlight.tag);
    [cell.contentView addSubview:switchlight];
    return cell;
}

-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if (self.nDevices.count > 1 )return [NSString stringWithFormat:@"%d Found 编译时间:%s,%s",self.nDevices.count,__DATE__,__TIME__];
        else return [NSString stringWithFormat:@"%d Found(增加了同步命令) 编译时间:%s,%s",self.nDevices.count,__DATE__,__TIME__];

    }
    return @"";
}

-(float) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 150.0f;
}

#pragma mark 开始连接设备
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CBPeripheral *p = [self.nDevices objectAtIndex:indexPath.row];
      NSLog(@"开始连接的设备是:%d,名字:%@",indexPath.row,p.name);
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];  //暂时不选中.
    
    p.delegate = self;
    [mCentralManager connectPeripheral:p options:nil];  //连接蓝牙设备。。。。。
    
    mCurrentConnectPeripheral=p;
    [self showProgressHub];
    [mCentralManager  stopScan];
    isReScan=NO;  //用户点击连接的时候, 不在搜索.
    isJustOpen=NO;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    CBPeripheral *p = [self.nDevices objectAtIndex:indexPath.row];
    if([myDelegate.peripheralArray containsObject:p])
    {
        [myDelegate.peripheralArray removeObject:p];
        NSLog(@"peripheralArray 删除 object %@, peripheralArray 剩余个数:%d",p.name,myDelegate.peripheralArray.count);
    }
    [self.mCentralManager cancelPeripheralConnection:p];  //开始断开.
}
#pragma mark - 开始搜索 
//CBCentralManager delegate
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    if (central.state != CBCentralManagerStatePoweredOn) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"当前设备不支持蓝牙4.0BLE!" message:[NSString stringWithFormat:@"CoreBluetooth return state: %d",central.state] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }else {
        [central scanForPeripheralsWithServices:nil options:nil];  //开始搜索
         NSLog(@"scan For Perpheral with Services ......");
    }
}
#pragma  mark 扫描到设备
//发现蓝牙设备,发现后直接显示到界面, 在选中后连接.
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    
    if ([self.nDevices containsObject:peripheral]==NO)
    {
        [self.nDevices addObject:peripheral];
        [self.tableView reloadData];
    }
    if (isJustOpen && [self.nLastConnDevices count]>0 && mCurrentConnectPeripheral==NULL)
    {
        NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, peripheral.UUID)];
        if ([self.nLastConnDevices containsObject:strUUID])
        {
            [self.nLastConnDevices removeObject:strUUID];  //删除这个.
             peripheral.delegate = self;
            
            [mCentralManager connectPeripheral:peripheral options:nil];  //连接蓝牙设备。。。。。
            
            mCurrentConnectPeripheral=peripheral;
            [self showProgressHub];
       }
    }
}
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"%@, didConnectPeripheral!",peripheral.name);
    peripheral.delegate=self;
    [peripheral discoverServices:nil];  //连接好,找services
    
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    [self hideProgressHub];
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"连接蓝牙失败..."] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    if([myDelegate.peripheralArray containsObject:peripheral])
    {
        [myDelegate.peripheralArray removeObject:peripheral];
        NSLog(@"peripheralArray 删除 object %@, peripheralArray 剩余个数:%d",peripheral.name,myDelegate.peripheralArray.count);
    }
    
}
#pragma mark 蓝牙断开.
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    /*
     如在连接中断开, 则会返回这样的信息.
     Error Domain=CBErrorDomain Code=6 "The connection has timed out unexpectedly." UserInfo=0x17860910 {NSLocalizedDescription=The connection has timed out unexpectedly
     
     Error Domain=CBErrorDomain Code=6 "The connection has timed out unexpectedly." UserInfo=0x155bc8b0 {NSLocalizedDescription=The connection has timed out unexpectedly.
     */
    NSLog(@"蓝牙断开===========error:%@",error);
    [self hideProgressHub];
    
    //mCentralManager retrieveConnectedPeripherals
    
    //如果是扫描时发送的断开,这里不提示.
    if (isReScan==NO) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"蓝牙<%@>已断开",peripheral.name] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
    [self setDevDisconnect:peripheral];
}
#pragma mark 设置设备连接上.
//这个设备连接上, 是在点击连接后开始连接的, 故单位时间内只有一个在活动.
-(void)setDevConnect
{
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    if ([myDelegate.peripheralArray containsObject:mCurrentConnectPeripheral]==NO)
    {
        [myDelegate.peripheralArray addObject:mCurrentConnectPeripheral];
        [BLEUtility enAbleReadCharacteristic:mCurrentConnectPeripheral];  //开启..
        NSLog(@"perpheralArray count is%lu  增加外设 %@",(unsigned long)myDelegate.peripheralArray.count,mCurrentConnectPeripheral.name);
        
        int idx=(int)[self.nDevices indexOfObject:mCurrentConnectPeripheral];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewRowAnimationNone];
        if(isNewPasswd)
        {
            [self saveBondPasswd];
            isNewPasswd=NO;
        }
        mCurrentConnectPeripheral=NULL;
        if (isJustOpen)
        {
            [self autoConnectNextDevice];
        }
        [self sendSyncCmdPkg];
    }else{  //如有以为问题, 则断开.
        [self setDevDisconnect:mCurrentConnectPeripheral];
    }
   
}
#pragma mark 设置设备断开
-(void)setDevDisconnect:(CBPeripheral *)peripheral
{
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    if([myDelegate.peripheralArray containsObject:peripheral])
    {
        [myDelegate.peripheralArray removeObject:peripheral];
        NSLog(@"peripheralArray 已删除对象 %@, peripheralArray 当前个数:%lu",peripheral.name,(unsigned long)myDelegate.peripheralArray.count);
    }
    [self.mCentralManager cancelPeripheralConnection:peripheral];  //
    mCurrentConnectPeripheral=NULL;
    if (isJustOpen)
    {
        [self autoConnectNextDevice];
    }
    if (isReScan==NO) {
        int idx=(int)[self.nDevices indexOfObject:peripheral];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}
#pragma  mark CBPeripheral的代理.
#pragma  mark 找到服务
-(void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    BOOL found = NO;
    NSLog(@"%@, didDiscoverServices!",peripheral.name);
    
    for (CBService *s in peripheral.services)
    {
        NSLog(@"Service found UUID is: %@",s.UUID);  //这里到UUID是 Service到UUId， 不是characteristic到UUID
        if([s.UUID isEqual:[CBUUID UUIDWithString:@"00001910-0000-1000-8000-00805f9b34fb"]]){
            NSLog(@"This is a Wanted Device !");
            found = YES;
        }
    }
    [self hideProgressHub];
    int idx=(int)[self.nDevices indexOfObject:peripheral];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
    
    if (found==NO)
    {
        //停止选中状态.
        NSString *string=[NSString stringWithFormat:@"%@,不是要的蓝牙电子设备.",peripheral.name];
        [self.view makeToast2:string];
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    }else{
        for (CBService *s in peripheral.services)
            [peripheral discoverCharacteristics:nil forService:s];
    }
   
}
-(void) peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
   // NSLog(@"Device %@ didUpdateNotificationStateForCharacteristic error = %@",peripheral.name,error);
}
#pragma mark 找到特征值
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    NSLog(@"找到服务中的特征值:%@",service.UUID.description);
    if ([service.UUID isEqual:[CBUUID UUIDWithString:UUID_SERVICE]])
    {
        [BLEUtility enAbleReadCharacteristic:peripheral];  //开启特征值的读取模式.
        //接下来发送当前时间.
        [self sendBondPasswd];
    }
}
-(void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray *)invalidatedServices
{
    NSLog(@"Device: %@ didModifyServices",peripheral.name);
}
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
    NSLog(@"Device: %@ didUpdateValueForDescriptor",peripheral.name);
}
-(void) peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
   // NSLog(@"didWriteValueForCharacteristic %@ error = %@",characteristic,error);
}
-(void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
 //  NSLog(@"Device: %@ didWriteValueForDescriptor",peripheral.name);
}
-(void)peripheralDidUpdateName:(CBPeripheral *)peripheral
{
    int idx=[self.nDevices indexOfObject:peripheral];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
    
    UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.text = peripheral.name;  //更新名字;
    NSLog(@"peripheralDidUpdateName:%@",peripheral.name);
}

#pragma mark 接收数据.
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"收到数据 = %@",characteristic.UUID);
    
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUID_READ]])
    {
        NSData *buffer=characteristic.value;
        uint8_t *pTmp=(uint8_t *)[buffer bytes];
        
        NSString *tmpStr=[[NSString alloc] init];
        for (int i=0; i<buffer.length; i++) {
            NSString *str1=[NSString stringWithFormat:@" 0x%02x",pTmp[i]];
            tmpStr=[tmpStr stringByAppendingString:str1];
        }
        NSLog(@"dev: %@,rcv data(hex):%@",peripheral.name,tmpStr);
        [self parseRcvData:buffer p:peripheral];
    }
}


#pragma mark - 解析收到的数据
//流程是: 先判断长度,--->校验和---->解密.
-(void) parseRcvData:(NSData *)data p:(CBPeripheral *)peripheral
{
    if(data.length>8)
    {
        if([CmdData checkRcvData:data])//校验成功.
        {
            uint8_t *pData=(uint8_t *)[data bytes];
             int index=(int)pData[5];
            if(index>0)  //接收的数据包加密了.
            {
                [CmdData DecryptCode:pData];
            }
            if(pData[4]==0x01)  //返回的是设备状态信息.
            {
                    [self setDevConnect];
                
             }
            else if(pData[4]==CMD_WORD_RET_E)
            {
                if(pData[7]==0x04)
                {
                    NSLog(@"不是当前设备,设备码错误");
                    [self setDevDisconnect:mCurrentConnectPeripheral];
                }else if(pData[7]==0x05){  //绑定的密码错误.
                    [self showBondPasswdDialog:@"输入密码错误,请重新输入."];
                }else{
                      NSLog(@"接收数据错误, 错误码是: %d",pData[7]);
                }
            }
            
            else if(pData[4]==CMD_WORD_RET_U)
            {
                NSLog(@"数据发送错误, 未定义的类型");
            }
            else if(pData[4]==CMD_WORD_RET_G)
            {
                  NSLog(@"数据发送成功,命令是:%c",pData[7]);
                  uint8_t rcvCmd=pData[7];
                if(rcvCmd==CMD_WORD_N)
                {
                    [self setDevDisconnect:peripheral];
                    NSLog(@"设置名字成功,请重连设备.");
                }
                else if(rcvCmd==CMD_WORD_P)
                {
                    NSLog(@"设置密码成功,请重连设备.");
                    [self setDevDisconnect:peripheral];
                }
            }
        }else{
            NSLog(@"parseRcvData Error, checkData Error");
        }
    }else{  
        NSLog(@"接收数据包不完整.");
    }
}
#pragma mark - 进度条处理
-(void)showProgressHub
{
    
    mProgressHub = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    [self.navigationController.view addSubview:mProgressHub];
    
    mProgressHub.delegate = self;
    mProgressHub.labelText = @"连接中...";
    [mProgressHub show:YES];
    
    //10second
    mProgressTimer=[NSTimer scheduledTimerWithTimeInterval: 10
                                                    target: self
                                                  selector: @selector(ProgressHubTimeout:)
                                                  userInfo: nil
                                                   repeats: NO];
}
-(void)hideProgressHub
{
    if (mProgressHub!=NULL)
        [mProgressHub hide:YES];  //在hide回调中有停止timer
    if (mProgressTimer!=NULL) {
        [mProgressTimer invalidate];
        mProgressTimer=NULL;
    }
}
- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [mProgressHub removeFromSuperview];
    mProgressHub= NULL;
}
-(void)ProgressHubTimeout: (NSTimer *) timer
{
    NSLog(@"progress hub time out.....连接超时");
    [self hideProgressHub];
    //取消当前连接. 连接失败.
    int idx=[self.nDevices indexOfObject:mCurrentConnectPeripheral];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)sendSyncCmdPkg: (NSTimer *) timer
{
    NSLog(@"send sync cmd pkg....");
    NSData *data=[CmdData getSyncBianArray];
    [BLEUtility writeData:data];
    //    [self.view makeToast2:@"已发送一键白光"];
}
-(void) sendSyncCmdPkg
{
    NSLog(@"send sync cmd pkg....");
    NSData *data=[CmdData getSyncBianArray];
    [BLEUtility writeData:data];
}
-(void)showWarnDialog
{
    if (isShowWarning) {
        return ;
    }
    isShowWarning=true;
    mWarnAlertView = [[UIAlertView alloc]initWithTitle:@"警告" message:[NSString stringWithFormat:@"设备已远离!!"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [mWarnAlertView show];
    mWarnAlertView.tag=WARN_DIALOG_TAG;
}
-(void)hideWarnDialog
{
    isShowWarning=false;
    [mWarnAlertView dismissWithClickedButtonIndex:0 animated:NO];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==BOND_PASSWD_DIALOG_TAG) {  //绑定的密码对话框
        
        NSString *str=[alertView textFieldAtIndex:0].text;
        NSLog(@"输入的绑定密码是: %@",str);
        isNewPasswd=YES;
        mConnectingPasswd=str;
        [self sendBondPasswdPkg:mCurrentConnectPeripheral passwd:str];
    }else if(alertView.tag==WARN_DIALOG_TAG){
        isShowWarning=false;
    }
   
}
#pragma mark - 密码的操作

-(void) sendBondPasswd
{
    NSString *passwd=[self getBondPasswd];
    if(passwd==NULL){  //先取消连接进度hud
        [self showBondPasswdDialog:@"请输入密码."];
    }else{  //有密码,则发送
        [self sendBondPasswdPkg:mCurrentConnectPeripheral passwd:passwd];
    }
}
-(void) sendBondPasswdPkg:(CBPeripheral *)peripheral passwd:(NSString *)passwd
{
     NSData *data=[CmdData getBondPasswdArray:passwd];
    [BLEUtility writeBondPasswdData:data p:peripheral];
}
-(void) showBondPasswdDialog:(NSString *)message
{
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:message message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
    
    alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
    [alertView textFieldAtIndex:0].placeholder=@"密码最大6个数字";
    [alertView textFieldAtIndex:0].keyboardType=UIKeyboardTypeNumberPad;
    [alertView show];
    alertView.tag=BOND_PASSWD_DIALOG_TAG;

}
-(NSString *)getBondPasswd
{
    NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, mCurrentConnectPeripheral.UUID)];
   	NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *value=NULL;
    value = [ud objectForKey:strUUID];
     NSLog(@"get bond pass word--获取绑定的密码--->%@",value);
    return value;
}
-(void)saveBondPasswd
{
    NSLog(@"save bond pass word----->");
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, mCurrentConnectPeripheral.UUID)];
    [ud setObject:mConnectingPasswd  forKey:strUUID];
    mConnectingPasswd=NULL;
}
- (void)switchBtnChanged:(UISwitch*)sender
{
    NSInteger tag=sender.tag;
    CBPeripheral *p = [self.nDevices objectAtIndex:tag];
    if (p.isConnected)
    {
        NSData *data=[CmdData getOpenLight:sender.isOn];
        [BLEUtility writeBondPasswdData:data p:p];
    }
}
-(void) autoConnectNextDevice
{
   
    if ( mCurrentConnectPeripheral==NULL)
    {
        if ([self.nLastConnDevices count]>0)
        {
            //从 ndevices中获取一个设备.
            NSString *strSave=[self.nLastConnDevices objectAtIndex:0];
            
            for (int i=0; i<[self.nDevices count]; i++)
            {
                CBPeripheral *peripheral=[self.nDevices objectAtIndex:i];
                 NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, peripheral.UUID)];
                if ([strUUID isEqualToString:strSave])  //找到一个设备, 开始连接.
                {
                    [self.nLastConnDevices removeObject:strUUID];
                    peripheral.delegate = self;
                    [mCentralManager connectPeripheral:peripheral options:nil];  //连接蓝牙设备。。。。。
                    
                    mCurrentConnectPeripheral=peripheral;
                    [self showProgressHub];
                    break;
                }
            }
        }
    }
}
#pragma mark 获取上次连接的设备.
-(int) getLastConnecteDevice
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    NSString *strCnt=NULL;
    int count=0;
    strCnt = [ud objectForKey:@"LASTCONN_DEV_COUNT"];
    [self.nLastConnDevices removeAllObjects];
    
    if (strCnt!=NULL)
    {
        count=[strCnt intValue];
        NSLog(@"getLastConnecteDevice last connected count: %d",count);
        for (int i=0; i<count; i++)
        {
            NSString *strKEY=[NSString stringWithFormat:@"%@=%d",@"LASTCONNDEV",i];
            NSString *value = [ud objectForKey:strKEY];
            if (value!=NULL)
            {
                 [self.nLastConnDevices addObject:value];
            }
            NSLog(@"getLastConnecteDevice last connected device: %d,value=%@",i,value);
        }
    }
    
    return count;
}
#pragma mark 保存已连接的设备.
-(void)saveConnectedDevice
{
    AppDelegate *myDelegate=[[UIApplication sharedApplication] delegate];
    
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    
    NSString *strCount=[NSString stringWithFormat:@"%d",[myDelegate.peripheralArray count]];
    [ud setObject:strCount  forKey:@"LASTCONN_DEV_COUNT"];
     NSLog(@"saveConnectedDevice lperipheralArray count: %d",[myDelegate.peripheralArray count]);
    for (int i=0; i<[myDelegate.peripheralArray count]; i++)
    {
        CBPeripheral *peripheral=[myDelegate.peripheralArray objectAtIndex:i];
        NSString *strUUID=[NSString stringWithFormat:@"%@",CFUUIDCreateString(nil, peripheral.UUID)];
        NSString *strKEY=[NSString stringWithFormat:@"%@=%d",@"LASTCONNDEV",i];
        [ud setObject:strUUID forKey:strKEY];
        NSLog(@"saveConnectedDevice last connected device: %d,value=%@",i,strUUID);
    }
}
@end
